Perform a series of commands repeatedly: either the specified number of times or until break is encountered.
Loop [, Count]
Count | How many times (iterations) to perform the loop. If omitted, the Loop continues indefinitely until a break or return is encountered. If Count is a variable reference such as %ItemCount%, the loop is skipped entirely whenever the variable is blank or contains a number less than 1. Due to the need to support file-pattern loops, Count cannot be an expression. However, as with all non-expression parameters, an expression can be forcibly used by preceding it with a % and a space. For example: Loop % Count + 1. In such cases, the expression is evaluated only once, right before the loop begins. |
The loop command is usually followed by a block, which is a collection of statements that form the body of the loop. However, a loop with only a single command does not require a block (an if-else compound statement counts as a single command for this purpose).
A common use of this command is an infinite loop that uses the break command somewhere in the loop's body to determine when to stop the loop.
The use of break and continue inside a loop are encouraged as alternatives to goto, since they generally make a script more understandable and maintainable. To create a "While" loop, make the first statement of the loop's body an IF statement that conditionally issues the break command. To create a "Do...While" loop, use the same technique except put the IF statement as the last statement in the loop's body.
The built-in variable A_Index contains the number of the current loop iteration. For example, the first time the script executes the loop's body, this variable will contain the number 1. For the second time, it will contain 2, and so on. If an inner loop is enclosed by an outer loop, the inner loop takes precedence. The value will be 0 whenever the variable is referenced outside of a loop. This variable works inside all types of loops, including file-loops and registry-loops.
In v1.0.41+, the One True Brace (OTB) style may optionally be used with normal loops (but not specialized loops such as file-pattern and parsing). For example:
Loop { ... } Loop %RepeatCount% { ... }
Specialized loops: Loops can be used to automatically retrieve files, folders, or registry items (one at a time). See file-loop and registry-loop for details. In addition, file-reading loops can operate on the entire contents of a file, one line at a time. Finally, parsing loops can operate on the individual fields contained inside a delimited string.
File loop, Registry loop, File-read loop, Parsing loop, Break, Continue, Blocks
Loop, 3 { MsgBox, Iteration number is %A_Index%. ; A_Index will be 1, 2, then 3 Sleep, 100 } Loop { if a_index > 25 break ; Terminate the loop if a_index < 20 continue ; Skip the below and start a new iteration MsgBox, a_index = %a_index% ; This will display only the numbers 20 through 25 }